import sys

from docx import Document
import os
from datetime import datetime
import re
def get_current_directory():
    """
    获取当前程序运行的目录，支持打包为EXE后的环境
    """
    # 获取当前执行文件的路径
    if getattr(sys, 'frozen', False):
        # 当程序被打包为EXE时
        # sys.executable指向打包后的EXE文件路径
        current_path = os.path.dirname(sys.executable)
    else:
        # 开发环境中，__file__指向当前脚本文件
        current_path = os.path.dirname(os.path.abspath(__file__))

    # 规范化路径（处理斜杠/反斜杠问题）
    current_path = os.path.normpath(current_path)
    print(current_path)
    return current_path
def replace_placeholders_in_run(run, placeholders):
    """替换单个run中的占位符，不影响图片"""
    if not run.text:
        return False  # 空文本不处理

    modified = False
    original_text = run.text
    pattern = re.compile(r'\{\{([\w\-_]+)\}\}')  # 支持复杂占位符

    # 查找所有占位符
    matches = pattern.findall(original_text)
    if not matches:
        return False

    # 保存原始格式
    font = run.font
    original_font_name = font.name
    original_font_size = font.size
    original_bold = font.bold
    original_italic = font.italic
    original_underline = font.underline

    # 替换占位符
    new_text = original_text
    for key in matches:
        if key in placeholders:
            placeholder = f"{{{{{key}}}}}"
            new_text = new_text.replace(placeholder, str(placeholders[key]))
            modified = True

    if modified:
        run.text = new_text
        # 恢复格式
        run.font.name = original_font_name
        run.font.size = original_font_size
        run.font.bold = original_bold
        run.font.italic = original_italic
        run.font.underline = original_underline

    return modified


def replace_placeholders_in_paragraph(paragraph, placeholders):
    """替换段落中的占位符，确保保留所有图片"""
    # 遍历段落中的所有元素，只处理文本run，保留图片等其他元素
    for run in paragraph.runs:
        # 检查是否为图片（图片run通常包含特殊标记）
        if 'graphicData' in run._element.xml:
            continue  # 跳过图片元素

        # 处理文本run中的占位符
        replace_placeholders_in_run(run, placeholders)


def replace_placeholders_in_table(table, placeholders):
    """替换表格中的占位符"""
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                replace_placeholders_in_paragraph(paragraph, placeholders)


def fill_template(template_path, data, output_path=None):
    """将数据填充到Word模板中，完全保留图片"""
    try:
        # 验证输入
        if not os.path.exists(template_path):
            print(f"错误：模板文件不存在 - {template_path}")
            return None

        if not isinstance(data, dict):
            print("错误：数据必须是字典类型")
            return None

        # 加载模板文档
        doc = Document(template_path)

        # 替换正文中的占位符
        for paragraph in doc.paragraphs:
            replace_placeholders_in_paragraph(paragraph, data)

        # 替换表格中的占位符
        for table in doc.tables:
            replace_placeholders_in_table(table, data)

        # 处理输出路径
        if not output_path:
            base, ext = os.path.splitext(os.path.basename(template_path))
            timestamp = datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
            output_path = f"{base}_{timestamp}{ext}"

        # 保存填充后的文档
        doc.save(get_current_directory()+'/'+output_path)
        print(f"已成功填充模板并保存到: {os.path.normpath(output_path)}")
        return get_current_directory()+'/'+output_path

    except Exception as e:
        print(f"填充模板时出错: {str(e)}")
        return None
